package cn.wolfcode.shop.member.server.impl;

import cn.wolfcode.cloud.exception.BusinessException;
import cn.wolfcode.cloud.redis.RedisService;
import cn.wolfcode.shop.member.domain.User;
import cn.wolfcode.shop.member.mapper.MemberMapper;
import cn.wolfcode.shop.member.redis.MemberKeyPrefix;
import cn.wolfcode.shop.member.result.MemberServerCodeMsg;
import cn.wolfcode.shop.member.server.IMemberService;
import cn.wolfcode.shop.member.utils.MD5Utils;
import cn.wolfcode.shop.member.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class MemberServiceImpl implements IMemberService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public User get(Long id) {
        return memberMapper.get(id);
    }

    @Override
    public String login(LoginVo loginVo) {
        User user = get(Long.valueOf(loginVo.getUsername()));
        if(user == null){
            throw new BusinessException(MemberServerCodeMsg.USER_CODE_MSG);
        }

        String password = loginVo.getPassword();
        String salt = user.getSalt();
        String MD5password = MD5Utils.PassFromMD5(password, salt);
        String userpass = user.getPassword();
        System.out.println(MD5password);
        if(!MD5password.equals(user.getPassword())){
            throw new BusinessException(MemberServerCodeMsg.PASSWORD_CODE_MSG);
        }
        String token = createToken(user);
        return token;
    }

    @Override
    public boolean refreshCookie(String token) {
        boolean flag = redisService.exists(MemberKeyPrefix.MEMBER_TOKEN, token);
        if(flag){
            //重新设置过期时间
            redisService.expire(MemberKeyPrefix.MEMBER_TOKEN,token,
                    MemberKeyPrefix.MEMBER_TOKEN.getExpireSeconds());
        }
        return true;
    }

    @Override
    public User getCurrentUser(String token) {
        User user = redisService.get(MemberKeyPrefix.MEMBER_TOKEN, token, User.class);
        return user;
    }

    private String createToken(User user){
        String token= UUID.randomUUID().toString().replace("-","");
        redisService.set(MemberKeyPrefix.MEMBER_TOKEN,token,user);
        return token;
    }
}
